package ph.com.gs3.formalistics.fragments.workers;

import ph.com.gs3.formalistics.communicators.CommunicatorModule.ResultCode;
import ph.com.gs3.formalistics.managers.SessionManager;
import ph.com.gs3.formalistics.managers.SessionManager.LoginResult;
import ph.com.gs3.formalistics.model.valueobjects.business.User;
import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;

public class LoginWorkerFragment extends Fragment {

	public static final String TAG = LoginWorkerFragment.class.getSimpleName();

	private SignInCallback listener;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			listener = (SignInCallback) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement SignInCallback");
		}
	}

	public void signIn(final String server, final String email,
			final String password) {

		AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

			String message = "";
			LoginResult loginResult = null;

			@Override
			protected Boolean doInBackground(Void... arg0) {

				SessionManager sessionManager = SessionManager
						.getApplicationInstance();
				loginResult = sessionManager.login(server, email, password);

				switch (loginResult.loginResultCode) {
				// TODO: write the messages on xml instead of here
				case APPLICATION_ERROR:
					message = "The application encountered an unexpected error, please try again later.";
					break;
				case CONNECTION_FAILED:
					message = "Unable to connect to server, please contact your administrator";
					break;
				case INVALID_SERVER_RESPONSE:
					message = "The server gave an invalid response, please contact your administrator";
					break;
				case LOGIN_FAILED:
					message = loginResult.message;
					break;
				case SUCCESS:
					message = "Login Success";
				default:
					break;
				}

				//return (loginResult.loginResultCode == ResultCode.SUCCESS);
				return true;
			}

			@Override
			protected void onPostExecute(Boolean success) {
				super.onPostExecute(success);

				if (success) {
					listener.onSignInSuccess(loginResult.activeUser);
				} else {
					listener.onSignInFail(message);
				}
			}

		};

		task.execute();

	}

	public static interface SignInCallback {
		public void onSignInSuccess(User activeUser);

		public void onSignInFail(String failureMessage);
	}

}
